<template>
	<!-- 上传照片组件 -->
	<view class="uploadImg">
		<view class="upload-box">
			<view v-if="choiceList.length>0" class="uploadList" v-for="(item,index) in choiceList" :key="index">
				<image :src="item" mode="aspectFill"></image>
				<view class="delete" @tap="deleteChoice(index)">X</view>
			</view>
			<view class="camera" @tap="upLoad">
				<text class="icon iconfont icon-shangchuanzhaopian"></text>
			</view>
		</view>
	</view>
</template>

<script>
	import util from '@/component/commen/api/util.js';
	export default {
		data() {
			return {
				choiceList: [], //选择的图片
			}
		},
		methods: {
			upLoad() { //点击上传图片
				// console.log("数组中图片：",this.choiceList)
				if (this.choiceList.length >= 3) {
					return uni.showToast({
						title: "最多只能选择3张！",
						icon: "none"
					})
				}
				uni.chooseImage({
					count: 1, // 可选择图片的数量
					sizeType: ['compressed'], // 压缩图片
					sourceType: ['album'], // 从相册选择图片
					success: (res) => {
						console.log(res)
						this.pushImg(res.tempFilePaths[0])
						// this.choiceList.push(res.tempFilePaths);
					}
				});
			},
			deleteChoice(index) { //点击删除按钮
				this.choiceList.splice(index, 1);
				this.$emit("choiceImg",this.choiceList)
			},
			pushImg(imgData) { //将图片上传至服务器
				let filePath = imgData
				let name = "file"
				util.uploadImg(filePath,name).then(res=>{
					// console.log("获取线上图片地址：",res)
					this.choiceList.push(res)
					this.$emit("choiceImg",this.choiceList)
				})
			},
			clearn(value){
				// console.log(value)
				this.choiceList = []
			}
		}
	}
</script>

<style lang="scss" scoped>
	.uploadImg {
		.upload-box {
			margin-top: 40rpx;
			display: flex;
			flex-wrap: wrap;

			.uploadList {
				width: 150rpx;
				height: 150rpx;
				margin-right: 10rpx;
				margin-top: 20rpx;
				position: relative;

				image {
					width: 100%;
					height: 100%;
				}

				.delete {
					position: absolute;
					top: 0;
					right: 0;
					background: rgba(red, 0.8);
					color: #fff;
					width: 40rpx;
					text-align: center;
					height: 40rpx;
				}
			}

			.camera {
				margin-top: 20rpx;
				width: 150rpx;
				height: 150rpx;
				text-align: center;
				line-height: 150rpx;
				border-radius: 10rpx;
				background: #ededed;

				.icon-shangchuanzhaopian {
					font-size: 60rpx;
				}
			}
		}
	}
</style>